package com.quectel.cms.controller.household;


import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.quectel.cms.constants.CmsRedisCacheConstants;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.household.dto.HouseholdAuditDto;
import com.quectel.core.module.household.service.HouseholdAuditService;
import com.quectel.core.module.household.service.HouseholdRoomService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import com.quectel.util.redis.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

/**
 * @author rananxin
 * @date 2021-12-14 09:32:00
 */
@Slf4j
@RestController
@RequestMapping("householdAudit")
@Tag(name = "HouseholdAuditController", description = "人员审核表相关api")
public class HouseholdAuditController extends BaseController {

    @DubboReference
    private HouseholdAuditService householdAuditService;
    @DubboReference
    private HouseholdRoomService householdRoomService;
    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private VillageRoomService villageRoomService;


    private static final String HOUSEHOLD_AUDIT_LOCK = CmsRedisCacheConstants.PROJECT_NAME + "HOUSEHOLD_AUDIT_LOCK:";

    /**
     * 住户审核请求
     *
     * @param householdAuditDto
     * @return
     */
    @PostMapping("auditReq")
    @RequirePermissions(values = "householdAudit:edit")
    @Operation(summary = "处理住户审核请求")
    public Response<Object> auditReq(@RequestBody HouseholdAuditDto householdAuditDto) {
        HouseholdAuditDto auditDto = householdAuditService.selectById(householdAuditDto.getId());
        if (auditDto == null) {
            return Response.error("该审核记录不存在");
        }
        Byte auditStatus = householdAuditDto.getAuditStatus();

        if (HouseholdAuditDto.AuditStatusEnum.AUDIT_SUCCESS.getStatus().equals(auditStatus)) {
            // 审核通过，审查关系并绑定
            Lock spinLock = RedisUtils.getSpinLock(HOUSEHOLD_AUDIT_LOCK + auditDto.getId());
            spinLock.lock();
            try {
                VillageRoomDto villageRoomDto = villageRoomService.selectById(auditDto.getRoomId());
                if (villageRoomDto == null) {
                    return Response.error("该房屋不存在");
                }

                auditDto.setAuditStatus(householdAuditDto.getAuditStatus());
                auditDto.setAuditOpinion(householdAuditDto.getAuditOpinion());
                householdAuditService.audit(auditDto);
                return Response.ok();
            } catch (Exception e) {
                log.error("auditReq", e);
            } finally {
                spinLock.unlock();
            }
            return Response.error("审核异常，请联系管理员");
        } else if (HouseholdAuditDto.AuditStatusEnum.AUDIT_FAIL.getStatus().equals(auditStatus)) {
            HouseholdAuditDto newlyDto = new HouseholdAuditDto();
            newlyDto.setId(householdAuditDto.getId());
            newlyDto.setAuditStatus(householdAuditDto.getAuditStatus());
            newlyDto.setAuditOpinion(householdAuditDto.getAuditOpinion());
            super.fillEditCommonData(newlyDto);
            householdAuditService.updateById(newlyDto);
        }
        return Response.ok();
    }


    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "householdAudit:list")
    @Operation(summary = "住户审核记录分页列表")
    public Response<Page<HouseholdAuditDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like("name");

        super.fillAuthorityData(request.getParams());
        if (request.isNotBlank("statusesStr")) {
            String statusesStr = request.getString("statusesStr");
            request.getParams().put("statuses", StrUtil.splitTrim(statusesStr, ","));
        }
        int total = householdAuditService.queryTotal(request.getParams());

        List<HouseholdAuditDto> list = null;
        if (total > 0) {
            list = householdAuditService.queryList(request.getParams());
            for (HouseholdAuditDto householdAuditDto : list) {
                householdAuditDto.setName(DesensitizedUtil.chineseName(householdAuditDto.getName()));
                householdAuditDto.setMobile(DesensitizedUtil.mobilePhone(householdAuditDto.getMobile()));
                householdAuditDto.setCardNo(DesensitizedUtil.idCardNum(householdAuditDto.getCardNo(), 2, 2));
            }
        } else {
            list = new ArrayList<>();
        }

        Page<HouseholdAuditDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<HouseholdAuditDto>>ok().wrap(page);
    }


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "householdAudit:info")
    @Operation(summary = "住户审核查询单条记录")
    public Response<HouseholdAuditDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (householdAuditService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdAuditDto householdAuditDto = householdAuditService.selectById(id);

        return Response.<HouseholdAuditDto>ok().wrap(householdAuditDto);
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "householdAudit:edit")
    @Operation(summary = "保存住户审核单条记录")
    public Response<Object> save(@RequestBody @Validated HouseholdAuditDto householdAuditDto) {

        //填充基础数据
        fillSaveCommonData(householdAuditDto);

        householdAuditService.save(householdAuditDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "householdAudit:edit")
    @Operation(summary = "修改住户审核单条记录")
    public Response<Object> update(@RequestBody @Validated HouseholdAuditDto householdAuditDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(householdAuditDto.getId()));
        if (householdAuditService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(householdAuditDto);

        householdAuditService.updateById(householdAuditDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "householdAudit:delete")
    @Operation(summary = "批量删除存在的住户审核记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (householdAuditService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        householdAuditService.deleteBatch(ids);

        return Response.ok();
    }
}
